package com.chaihu.api.listener.user.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.api.listener.AbstractServiceApiListener;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.annotation.ChaihuListener;
import com.chaihu.core.context.DataFlowContext;
import com.chaihu.core.event.service.api.ServiceDataFlowEvent;
import com.chaihu.core.factory.AuthenticationFactory;
import com.chaihu.intf.user.QueryUsersService;
import com.chaihu.utils.constant.ServiceCodeConstant;
import com.chaihu.utils.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * 用户注册 侦听
 * Created by wuxw on 2018/5/18.
 */
@Slf4j
@ChaihuListener("loginPcOutServiceListener")
public class LoginPcOutServiceListener extends AbstractServiceApiListener {

    @Autowired
    private QueryUsersService queryUsersService;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "token", "未包含token");
    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
        String token = reqJson.getString("token");

        ResponseEntity responseEntity= null;
        try {
            // pc后台登出
            AuthenticationFactory.deleteToken(token);
            responseEntity = new ResponseEntity<String>("退出登录成功", HttpStatus.OK);
        } catch (Exception e) {
            log.error("登出异常：", e);
            ResponseResult responseResult = new ResponseResult(MsgCode.ERROR.getCode(), "退出登录失败，请联系管理员");
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(responseResult), HttpStatus.OK);
        }
        context.setResponseEntity(responseEntity);
    }

    @Override
    public String getServiceCode() {
        return ServiceCodeConstant.SERVICE_CODE_USER_SERVICE_PC_LOGINOUT;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }
}
